import { defineStore } from 'pinia';

/**
 * 计数器 Store
 * 
 * 此 store 管理应用程序中的计数器状态，
 * 包含状态、操作和 getter。
 * 
 * @returns {Object} 计数器 store 对象
 */
export const useCounterStore = defineStore('counter', {
  // 状态定义
  state: () => ({
    count: 0,
    lastUpdated: null,
    history: []
  }),
  
  // Getter 定义
  getters: {
    doubleCount: (state) => state.count * 2,
    formattedLastUpdated: (state) => {
      if (!state.lastUpdated) return 'Never updated';
      return new Date(state.lastUpdated).toLocaleString();
    },
    recentHistory: (state) => state.history.slice(-5).reverse()
  },
  
  // 操作定义
  actions: {
    /**
     * 增加计数器
     * @param {number} [amount=1] - 要增加的数量
     */
    increment(amount = 1) {
      this.count += amount;
      this.updateTimestamp();
      this.recordHistory(`Incremented by ${amount}`);
    },
    
    /**
     * 减少计数器
     * @param {number} [amount=1] - 要减少的数量
     */
    decrement(amount = 1) {
      this.count -= amount;
      this.updateTimestamp();
      this.recordHistory(`Decremented by ${amount}`);
    },
    
    /**
     * 重置计数器
     */
    reset() {
      this.count = 0;
      this.updateTimestamp();
      this.recordHistory('Reset counter');
    },
    
    /**
     * 更新最后修改时间戳
     */
    updateTimestamp() {
      this.lastUpdated = Date.now();
    },
    
    /**
     * 记录操作历史
     * @param {string} action - 执行的操作描述
     */
    recordHistory(action) {
      this.history.push({
        timestamp: Date.now(),
        action,
        count: this.count
      });
    }
  }
});